package com.xuehu.dao.user;

import com.mysql.cj.util.StringUtils;
import com.xuehu.dao.BaseDao;
import com.xuehu.pojo.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

public class UserDaoImpl implements UserDao {

    @Override
    public User getLoginUser(Connection connection, String userCode, String userPassword) throws Exception {

        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        User user = null;


        if (null != connection) {
            String sql = "select * from smbms_user where userCode = ? and userPassword = ?";
            Object[] params = {userCode, userPassword};

            resultSet = BaseDao.executeSelect(connection, preparedStatement, resultSet, sql, params);

            if (resultSet.next()) {
                user = new User();
                user.setId(resultSet.getInt("id"));
                user.setUserCode(resultSet.getString("userCode"));
                user.setUserName(resultSet.getString("userName"));
                user.setUserPassword(resultSet.getString("userPassword"));
                user.setGender(resultSet.getInt("gender"));
                user.setBirthday(resultSet.getDate("birthday"));
                user.setPhone(resultSet.getString("phone"));
                user.setAddress(resultSet.getString("address"));
                user.setUserRole(resultSet.getInt("userRole"));
                user.setCreatedBy(resultSet.getInt("createdBy"));
                user.setCreationDate(resultSet.getTimestamp("creationDate"));
                user.setModifyBy(resultSet.getInt("modifyBy"));
                user.setModifyDate(resultSet.getTimestamp("modifyDate"));
                return user;
            }
            BaseDao.closeResource(null, preparedStatement, resultSet);

        }
        return null;
    }

    //修改当前用户密码
    @Override
    public int updatePwd(Connection connection, int id, String password) throws Exception {
        PreparedStatement preparedStatement = null;

        String sql = "update smbms_user set userPassword = ? where id = ?";
        Object[] params = {password, id};
        AtomicInteger executeUpdate = new AtomicInteger();
        Optional.ofNullable(connection).ifPresent(u -> {
            try {
                executeUpdate.set(BaseDao.executeUpdate(connection, preparedStatement, sql, params));
            } catch (Exception e) {
                e.printStackTrace();
            }
            BaseDao.closeResource(connection, preparedStatement, null);
        });


        return executeUpdate.get();
    }

    //根据用户名和角色查询用户总数(最难理解的SQL)
    @Override
    public int getUserCount(Connection connection, String username, int userRole) throws Exception {

        PreparedStatement preparedStatement = null;

        ResultSet rs = null;

        int count = 0;

        if (connection != null) {
            StringBuffer sql = new StringBuffer();
            sql.append("select count(1) as count from smbms_user u, smbms_role r where u.userRole = r.id");
            ArrayList<Object> list = new ArrayList<>();

            if (!StringUtils.isNullOrEmpty(username)) {
                sql.append(" and u.userName like ?");
                list.add("%" + username + "%"); //index:0
            }

            if (userRole > 0) {
                sql.append(" and u.userRole = ?");
                list.add(userRole); //index:1
            }

            //怎么把list转换为数组
            Object[] params = list.toArray();

            //输出完整的sql语句
            System.out.println(sql.toString());


            rs = BaseDao.executeSelect(connection, preparedStatement, rs, sql.toString(), params);

            if (rs.next()) {
                count = rs.getInt("count"); //从结果集中获取最终的数量
            }

            BaseDao.closeResource(connection, preparedStatement, rs);

        }


        return count;
    }

    /**
     * 通过条件查询,获取用户列表
     *
     * @param connection
     * @param userName
     * @param userRole
     * @param currentPageNo
     * @param pageSize
     * @return
     * @throws Exception
     */
    @Override
    public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize)
            throws Exception {
        // TODO Auto-generated method stub
        PreparedStatement pstm = null;
        ResultSet rs = null;
        List<User> userList = new ArrayList<User>();
        if(connection != null){
            StringBuffer sql = new StringBuffer();
            sql.append("select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.userRole = r.id");
            List<Object> list = new ArrayList<Object>();
            if(!StringUtils.isNullOrEmpty(userName)){
                sql.append(" and u.userName like ?");
                list.add("%"+userName+"%");
            }
            if(userRole > 0){
                sql.append(" and u.userRole = ?");
                list.add(userRole);
            }
            sql.append(" order by creationDate DESC limit ?,?");
            currentPageNo = (currentPageNo-1)*pageSize;
            list.add(currentPageNo);
            list.add(pageSize);

            Object[] params = list.toArray();
            System.out.println("sql ----> " + sql.toString());
            rs = BaseDao.executeSelect(connection, pstm, rs, sql.toString(), params);
            while(rs.next()){
                User _user = new User();
                _user.setId(rs.getInt("id"));
                _user.setUserCode(rs.getString("userCode"));
                _user.setUserName(rs.getString("userName"));
                _user.setGender(rs.getInt("gender"));
                _user.setBirthday(rs.getDate("birthday"));
                _user.setPhone(rs.getString("phone"));
                _user.setUserRole(rs.getInt("userRole"));
                _user.setUserRoleName(rs.getString("userRoleName"));
                userList.add(_user);
            }
            BaseDao.closeResource(null, pstm, rs);
        }
        return userList;
    }

    @Override
    public int delUser(Connection connection, Integer userId) {

        PreparedStatement preparedStatement = null;

        String sql = "delete from smbms_user where id = ?";
        Object[] params = {userId};

        int executeUpdate = 0;

        if (null != connection) {
            try {
                executeUpdate = BaseDao.executeUpdate(connection, preparedStatement, sql, params);
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                BaseDao.closeResource(connection, preparedStatement, null);
            }
        }


        return executeUpdate;
    }


}
